/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller.report;

import com.thienloc.omap.controller.BaseBean;
import com.thienloc.omap.entity.RequestQueue;
import com.thienloc.omap.session.RequestQueueFacade;
import com.thienloc.omap.session.RequestQueueHistFacade;
import com.thienloc.omap.util.Constant;
import com.thienloc.omap.util.JsfUtil;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class ServiceReportBean extends BaseBean implements Serializable {

    @EJB
    private RequestQueueFacade requestQueueFacade;
    @EJB
    private RequestQueueHistFacade requestQueueHistFacade;
    private List<String> list = new ArrayList<String>();
    private Map<String, String> serviceMap;
    private RequestQueue selected;
    private Date startDate;
    private Date endDate;
    private String selectedRegion = Constant.MB_REGION;
    private String timeMode = "byDay";
//    private int month;
    private String days;
    private int year;
    private String syntaxString;
    private Properties properties = new Properties();
    private String searchMode = "byRegion";
    private final Logger logger = LoggerFactory.getLogger(ServiceReportBean.class);

    @PostConstruct
    public void init() {
        try {

            File file = new File(Constant.CONFIG_FOLDER + Constant.CONFIG_FILE_NAME);
            properties.load(new FileReader(file));

            String username = sessionBean.getOmapUser().getUsername();
            String lotteryServices = properties.getProperty("service." + username, "");
            String[] serviceNames = lotteryServices.split(",");

            serviceMap = new TreeMap<String, String>();
            for (String serviceName : serviceNames) {
                String abbr = properties.getProperty("service.abbr." + serviceName, "");
                serviceMap.put(abbr, serviceName);
            }
            selected = new RequestQueue();

            Calendar cal = Calendar.getInstance();
//            month = cal.get(Calendar.MONTH);
//            if (month == 0) {
//                month = 12;
//            }
            year = cal.get(Calendar.YEAR);
        } catch (IOException ex) {
            logger.error("[{}]: ", getUsername(), ex);
        }
    }

    public void search() {
//        String resourceName = "manage-customer-list-of-" + selected.getServiceName();
//        if (!sessionBean.hasRight(resourceName, "view")) {
//            JsfUtil.addErrorMessage("Lỗi phân quyền", "Bạn không có quyền lấy danh sách khách hàng của dịch vụ " + selected.getServiceName());
//            return;
//        }

        if (selected.getServiceName().equalsIgnoreCase("txtbase")) {
            List<String> syntaxList = Arrays.asList(syntaxString.split("\\r\\n"));
            for (String syntax : syntaxList) {
                syntax.trim();
                //cú pháp có thê chứa mã tỉnh phía sau
                String[] chunks = syntax.split(" ");
                String resource = "manage-customer-list-of-txtbase-" + chunks[0];
                if (!sessionBean.hasRight(resource, "view")) {
                    JsfUtil.addErrorMessage("Lỗi phân quyền", "Bạn không có quyền lấy danh sách khách hàng của dịch vụ " + syntax);
                    return;
                }
            }
        }

        list = new ArrayList<String>();
        if (timeMode.equalsIgnoreCase("byDay")) {
            list = searchByDay(startDate, endDate);
        } else {
            searchByMonth();
        }

        String[] permittedMdnSuffixesRange = properties.getProperty(
                "service." + sessionBean.getOmapUser().getUsername() + ".mdnSuffixRange." + selected.getServiceName(),
                "000,999").split(",");
        
        int suffixLength = permittedMdnSuffixesRange[1].length();
        int startRange = Integer.parseInt(permittedMdnSuffixesRange[0]);
        int endRange = Integer.parseInt(permittedMdnSuffixesRange[1]);

        for (int i = list.size() - 1; i >= 0; i--) {
            String mdn = list.get(i);
            int mdnSuffix = Integer.parseInt(mdn.substring(mdn.length() - suffixLength));
            if (mdnSuffix < startRange || mdnSuffix > endRange) {
                list.remove(i);
            }
        }
        Collections.sort(list);
    }

    private List<String> searchByDay(Date startDate, Date endDate) {
        List<String> result = new ArrayList<String>();

        List<String> mdn;
        if (searchMode.equalsIgnoreCase("byRegion")) {
            if (selected.getServiceName().equalsIgnoreCase("txtbase")) {
                List<String> syntaxList = Arrays.asList(syntaxString.split("\\r\\n"));
                for (String string : syntaxList) {
                    string.trim();
                }
                mdn = requestQueueFacade.findTxtBaseUsers(syntaxList, startDate, endDate, selected.getDeliverProvider());
            } else {
                mdn = requestQueueFacade.find(selectedRegion, selected.getServiceName(), startDate, endDate, selected.getDeliverProvider());
            }
        } else {
            List<String> syntaxList = Arrays.asList(syntaxString.split("\\r\\n"));
            for (String string : syntaxList) {
                string.trim();
            }
            mdn = requestQueueFacade.findUsersBySyntax(syntaxList, startDate, endDate, selected.getServiceName(), selected.getDeliverProvider());
        }

        mdn.removeAll(result);
        result.addAll(mdn);

        List<String> mdnHist;
        if (searchMode.equalsIgnoreCase("byRegion")) {
            if (selected.getServiceName().equalsIgnoreCase("txtbase")) {
                List<String> syntaxList = Arrays.asList(syntaxString.split("\\r\\n"));
                for (String string : syntaxList) {
                    string.trim();
                }
                mdnHist = requestQueueHistFacade.findTxtBaseUsers(syntaxList, startDate, endDate, selected.getDeliverProvider());
            } else {
                mdnHist = requestQueueHistFacade.find(selectedRegion, selected.getServiceName(), startDate, endDate, selected.getDeliverProvider());
            }
        } else {
            List<String> syntaxList = Arrays.asList(syntaxString.split("\\r\\n"));
            for (String string : syntaxList) {
                string.trim();
            }
            mdnHist = requestQueueHistFacade.findUsersBySyntax(syntaxList, startDate, endDate, selected.getServiceName(), selected.getDeliverProvider());
        }




        mdnHist.removeAll(result);
        result.addAll(mdnHist);

        return result;
    }

    private void searchByMonth() {
        String[] dayStrings = days.split(",");
        Calendar endTime = Calendar.getInstance();
//        endTime.set(Calendar.MONTH, month - 1);
        endTime.set(Calendar.SECOND, 0);

        if (selectedRegion.equalsIgnoreCase(Constant.MB_REGION)) {
            endTime.set(Calendar.HOUR_OF_DAY, 20);
            endTime.set(Calendar.MINUTE, 0);
        } else if (selectedRegion.equalsIgnoreCase(Constant.MT_REGION)) {
            endTime.set(Calendar.HOUR_OF_DAY, 17);
            endTime.set(Calendar.MINUTE, 30);
        } else if (selectedRegion.equalsIgnoreCase(Constant.MN_REGION)) {
            endTime.set(Calendar.HOUR_OF_DAY, 16);
            endTime.set(Calendar.MINUTE, 30);
        }

        for (String dayString : dayStrings) {
            String[] dayAndMonth = dayString.split("/");
            String day = dayAndMonth[0];
            String month = dayAndMonth[1];

            endTime.set(Calendar.DATE, Integer.parseInt(day));
            endTime.set(Calendar.MONTH, Integer.parseInt(month) - 1);
            Calendar startTime = Calendar.getInstance();
            startTime.setTime(endTime.getTime());
            startTime.add(Calendar.DATE, -1);

            List<String> mdnsInDay = searchByDay(startTime.getTime(), endTime.getTime());
            for (String mdn : mdnsInDay) {
                if (!list.contains(mdn)) {
                    list.add(mdn);
                }
            }
        }
    }

    public Map<String, String> getServiceMap() {
        return serviceMap;
    }

    public void setServiceMap(Map<String, String> serviceMap) {
        this.serviceMap = serviceMap;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public RequestQueue getSelected() {
        return selected;
    }

    public void setSelected(RequestQueue selected) {
        this.selected = selected;
    }

    public String getSelectedRegion() {
        return selectedRegion;
    }

    public void setSelectedRegion(String selectedRegion) {
        this.selectedRegion = selectedRegion;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public String getTimeMode() {
        return timeMode;
    }

    public void setTimeMode(String timeMode) {
        this.timeMode = timeMode;
    }

    public String getDays() {
        return days;
    }

    public void setDays(String days) {
        this.days = days;
    }

    public String getSearchMode() {
        return searchMode;
    }

    public void setSearchMode(String searchMode) {
        this.searchMode = searchMode;
    }

//    public int getMonth() {
//        return month;
//    }
//
//    public void setMonth(int month) {
//        this.month = month;
//    }
    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getSyntaxString() {
        return syntaxString;
    }

    public void setSyntaxString(String syntaxString) {
        this.syntaxString = syntaxString;
    }
}
